import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:zhaoxiaowu_app/eventbus/event_bus.dart';
import 'package:zhaoxiaowu_app/global/global.dart';
import 'package:zhaoxiaowu_app/utils/date/date_utils.dart';

class DateAlertList extends StatefulWidget {
  const DateAlertList({Key key}) : super(key: key);

  @override
  _DateAlertListState createState() => _DateAlertListState();
}

class _DateAlertListState extends State<DateAlertList> {
  List _data;
  @override
  void initState() {
    // TODO: implement initState
    bus.on("date_list", (arg) {
      loadData();
    });
    super.initState();
    loadData();
    var data = LunarCalendarUtil.lunarToSolar(
        2021, 8, 15, LunarCalendarUtil.leapMonth(2021) == 0 ? false : true);
    DateTime datetime = DateTime(data[0], data[1], data[2]);
    DateTime datetime2 =
        DateTime(DateTime.now().year, DateTime.now().month, DateTime.now().day);
    print(datetime2);
    print(datetime);
    print(datetime.difference(datetime2).inDays);
  }

  @override
  void dispose() {
    bus.off("date_list");
    super.dispose();
  }

  Widget _itemBuilder(context, index) {
    return Row(
      children: [
        Expanded(
          child: Text(_data[index]["name"]),
        ),
        IconButton(
            onPressed: () async {
              var result = await Global.getInstance().dio.delete(
                "/zxw/DateMessage",
                queryParameters: {
                  "id": _data[index]["id"],
                },
              );
              if (result.data["success"]) {
                loadData();
              } else {
                EasyLoading.showError(result.data["msg"]);
              }
            },
            icon: Icon(Icons.delete)),
      ],
    );
  }

  @override
  Widget build(BuildContext context) {
    return ListView.builder(
      itemCount: _data == null ? 0 : _data.length,
      itemBuilder: _itemBuilder,
    );
  }

  void loadData() async {
    setState(() {
      _data = [];
    });
    var result = await Global.getInstance().dio.get("/zxw/DateMessage");
    print(result.data);
    if (result.data["success"]) {
      setState(() {
        _data = result.data["data"];
      });
    } else {
      EasyLoading.showError(result.data["msg"]);
    }
  }
}
